package br.com.financas.bean;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.financas.abstractions.IUsuarioService;
import br.com.financas.entity.Usuario;
import br.com.financas.service.UsuarioService;
import br.com.financas.util.Criptografia;

@ManagedBean
@ViewScoped
public class LoginBean extends AbstractBean implements Serializable {
	
	private static final long serialVersionUID = -3215949664887916909L;

	@ManagedProperty(value = UsuarioBean.INJECTION_NAME)
	private UsuarioBean usuarioBean;
    private IUsuarioService<Usuario> usuarioService;
    private Usuario usuario = new Usuario(); 
	private String username;
	private String senha;
	private int acesso=0;
	
	public LoginBean(){
		usuarioService =  new UsuarioService();
	}
	
	public int getAcesso() {
		return acesso;
	}
	public void setAcesso(int acesso) {
		this.acesso = this.acesso + acesso;
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSenha() {
		return senha;
	}
	public void setSenha(String senha) {
		this.senha = Criptografia.criptografar(senha);
	}
	
	public String logar(){
		String nextPage = "/index.xhtml";
		FacesContext fc = FacesContext.getCurrentInstance();
		
		usuario = usuarioService.validarUsuario(getUsername(), getSenha());
		
		if(usuario == null){
			displayWarnMessageToUser("login.validation");
			nextPage = null;
		}else{
			ExternalContext ec = fc.getExternalContext();
			HttpSession session = (HttpSession)ec.getSession(false);
			session.setAttribute("usuario", usuario);
			usuarioBean.setUsuario(usuario);
		}
		
		return nextPage;
	}
	
	public String registrar(){
		String nextPage = "/cadastrar-usuario.xhtml";
		return nextPage;
	}
	
	public void setUsuarioBean(UsuarioBean usuarioBean){
		this.usuarioBean = usuarioBean;
	}
	
}
